<template>
  <div v-loading="loading" class="app-container">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item name="1">
        <template slot="title">
          <i class="el-icon-search" />搜索栏
        </template>
        <div class="head-container">
          <el-form ref="searchForm" class="searchform" :model="params" :inline="true" size="mini" label-width="auto">
            <el-form-item label="流水号">
              <el-input v-model="params.vendorPortalId" size="mini" placeholder="输入流水号" clearable style="width: 200px;" />
            </el-form-item>
            <el-form-item label="条码">
              <el-input v-model="params.upcNbrs" placeholder="多个条码以逗号分割" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="商品号">
              <el-input v-model="params.itemNbr" placeholder="输入条码检验码/商品号搜索" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="部门">
              <el-input v-model="params.deptNbr" placeholder="输入部门搜索" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="商品说明1">
              <el-input v-model="params.item1Desc" placeholder="输入商品说明1模糊匹配" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="供应商之商品代码">
              <el-input v-model="params.vendorStockId" placeholder="输入供应商之商品代码" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="供应商编号">
              <el-input v-model="params.vendorNbr" placeholder="输入供应商编号" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="供应商名称">
              <el-input v-model="params.vendorName" placeholder="输入供应商名称模糊匹配" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="params.itemStatus" placeholder="选择搜索" clearable size="mini" style="width: 200px">
                <el-option :key="2" label="待数据校验" :value="2" />
                <el-option :key="3" label="数据校验中" :value="3" />
                <el-option :key="4" label="数据校验成功" :value="4" />
                <el-option :key="-4" label="数据校验失败" :value="-4" />
                <el-option :key="-6" label="BPMS审批驳回" :value="-6" />
                <el-option :key="-10" label="MDA审批驳回" :value="-10" />
                <el-option :key="-11" label="Item File审批驳回" :value="-11" />
                <el-option :key="-1" label="已作废" :value="-1" />
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间">
              <el-date-picker
                v-model="syncTime"
                size="mini"
                type="datetimerange"
                value-format="yyyy/MM/dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="syncTimeChange"
              />
            </el-form-item>
            <el-form-item label="是否成对商品" prop="queryPairingSubmitFlag">
              <el-checkbox v-model="params.queryPairingSubmitFlag" />
            </el-form-item>
            <el-form-item label="成对商品标识" prop="pairingSubmitFlag">
              <el-input v-model="params.pairingSubmitFlag" placeholder="输入成对商品标识" clearable size="mini" style="width: 200px;" />
            </el-form-item>
            <el-form-item>
              <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round icon="el-icon-refresh" @click="resetForm">重置</el-button>
              <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round icon="el-icon-search" @click="toQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div style="padding-top:5px">
      <el-button size="mini" type="danger" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-delete" round @click="doDeleteItem">作废</el-button>
      <el-upload
        ref="upload"
        :auto-upload="false"
        :on-change="handleFileChange"
        :show-file-list="false"
        :limit="1"
        :multiple="false"
        action="#"
        accept=""
        style="float:right;margin-left:0px;"
      >
        <el-button size="mini" type="primary" icon="el-icon-upload2" round>上传附件</el-button>
      </el-upload>
      <el-upload
        ref="upload"
        :auto-upload="false"
        :on-change="handleOnChange"
        :show-file-list="false"
        :limit="1"
        :multiple="false"
        action="#"
        accept=""
        style="float:right;margin-bottom:5px;margin-left:0px;"
      >
        <el-button size="mini" type="primary" icon="el-icon-upload2" round>导入Excel</el-button>
      </el-upload>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-download" round @click="doExportExcel">导出Excel</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-monitor" round @click="dobatchValidate">校验</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-edit" round @click="doClearSelection">取消选择</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-search" round @click="toQuery">刷新</el-button>
      <el-table
        ref="itemTab"
        :data="data"
        :row-key="getRowKeys"
        stripe
        size="small"
        border
        style="width: 100%;"
        @header-dragend="colChange"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column :reserve-selection="true" type="selection" align="center" width="55" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="流水号" prop="vendorPortalId" :width="colWidths.vendorPortalId" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="条码" prop="upcNbr" :width="colWidths.upcNbr">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="toItemInfo(scope.row)">{{ scope.row.upcNbr }}</el-button>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="商品号" prop="itemNbr" :width="colWidths.itemNbr" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="部门" prop="deptNbr" :width="colWidths.deptNbr" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="商品说明1" prop="item1Desc" :width="colWidths.item1Desc" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="供应商之商品代码" prop="vendorStockId" :width="colWidths.vendorStockId" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="供应商编号" prop="vendorNbr" :width="colWidths.vendorNbr" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="供应商名称" prop="vendorName" :width="colWidths.vendorName" />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="上传时间" prop="syncTime" :width="colWidths.syncTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.syncTime) }}</span>
          </template>
        </el-table-column>
        <piItemColForm />
        <itemStatusForm />
        <el-table-column :show-overflow-tooltip="true" sortable="custom" label="最近修改时间" prop="updatedTime" :width="colWidths.updatedTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updatedTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="toItemInfo(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page.sync="currentPage"
        :page-sizes="[10,50,100,500]"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
    <itemForm ref="itemForm" :parent="parent" />
  </div>
</template>

<script>
import itemForm from '@/views/new-item/info'
import initData from '@/utils/initData'
import { parseTime } from '@/utils/index'
import { Message } from 'element-ui'
import { uploadExcel, batchValidate, batchUpdateFilePath } from '@/api/new-item'
import { toItemInfo, doDeleteItem } from '@/utils/newItem'
import itemStatusForm from '@/views/part/itemStatus'
import piItemColForm from '@/views/part/piItemCol'
import { doDownload } from '@/api/download'
import { uploadFile } from '@/api/change-item'

export default {
  components: { itemForm, itemStatusForm, piItemColForm },
  mixins: [initData],
  data() {
    return {
      syncTime: [],
      parent: this,
      ids: [],
      loading: false,
      activeName: '1'
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    toItemInfo,
    doDeleteItem,
    beforeInit() {
      this.url = '/new-item/validateList'
      this.params.pageNum = this.page
      this.params.pageSize = this.size
      return true
    },
    // 上传时间日期组件触发
    syncTimeChange(val) {
      this.params.findSyncTimeStartDate = val[0]
      this.params.findSyncTimeEndDate = val[1]
    },
    // 列表排序触发
    sortChange(val) {
      let sortType = ''
      if (val.order === 'descending') {
        sortType = ' DESC'
      } else if (val.order === 'ascending') {
        sortType = ' ASC'
      }
      this.params.sort = val.prop + sortType
      this.init()
    },
    // 查询
    toQuery() {
      this.page = 0
      this.currentPage = 1
      if (this.params.upcNbrs) {
        this.params.upcNbrs = this.params.upcNbrs.trim().replaceAll('，', ',')
      }
      this.init()
      this.doClearSelection()
    },
    // 查询栏重置触发
    resetForm() {
      this.params = {}
      this.$set(this.params, 'queryPairingSubmitFlag', false)
      this.syncTime = []
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      this.ids = []
      val.forEach(item => {
        this.ids.push(item.id)
      })
    },
    // 翻页选择row的key值
    getRowKeys(row) {
      return row.id
    },
    // 批量导出
    doExportExcel() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要导出的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('确认导出选择的 ' + this.ids.length + ' 条item信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          doDownload('/new-item/exportExcel', { ids: this.ids }, 'new-item.xlsx').then(() => {
            this.loading = false
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 文件变动的钩子
    handleOnChange(file, fileList) {
      const ex = file.raw.name.substring(file.raw.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024
      if (ex !== 'xlsx') {
        Message({
          message: '请上传格式为 xlsx 的Excel文件。',
          type: 'error',
          duration: 3 * 1000
        })
        fileList.pop()
      } else if (size > 5) {
        Message({
          message: 'Excel文件大小必须小于5M。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      } else {
        this.loading = true
        var formData = new FormData()
        formData.append('file', file.raw)
        uploadExcel(formData).then(res => {
          this.toQuery()
          Message({
            message: '操作成功，上传数据行数：' + res,
            type: 'success',
            duration: 3 * 1000
          })
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
        fileList.pop()
      }
    },
    // 清空选择项
    doClearSelection() {
      this.$refs.itemTab.clearSelection()
    },
    // 批量校验
    dobatchValidate() {
      if (this.ids.length < 1) {
        Message({
          message: '请选择需要校验的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('确认校验选择的 ' + this.ids.length + ' 条item信息?', '校验数据', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          batchValidate({ ids: this.ids }).then(res => {
            this.$alert('校验处理中，请稍后刷新页面进行查询。', '提交成功', {
              confirmButtonText: '确定',
              type: 'success'
            })
            this.toQuery()
            this.loading = false
          }, error => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 文件变动的钩子-附件上传
    handleFileChange(file, fileList) {
      var size = file.size / 1024 / 1024
      if (size > 5) {
        Message({
          message: '文件大小必须小于5M。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      } else if (this.ids.length < 1) {
        Message({
          message: '请选择需要上传附件的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('状态为 待数据校验/数据校验失败 方可上传附件，附件上传会覆盖原有附件，是否上传？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          var formData = new FormData()
          formData.append('file', file.raw)
          uploadFile(formData).then(res => {
            if (res) {
              const filePath = res[0].fileUrl
              if (filePath) {
                batchUpdateFilePath({ ids: this.ids, filePath: filePath }).then(() => {
                  this.toQuery()
                  Message({
                    message: '上传成功。',
                    type: 'success',
                    duration: 3 * 1000
                  })
                  this.loading = false
                }, error => {
                  console.log(error)
                  this.loading = false
                })
              }
            }
          }, error => {
            console.log(error)
            this.loading = false
          })
          fileList.pop()
        })
      }
    }
  }
}
</script>
